﻿using System;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Threading;

namespace Flare
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var directoryName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            var fileName = System.IO.Path.Combine(directoryName, "flamedb.sdf");
            glob.DBConnection = string.Format("Data Source={0}; Persist Security Info=False;", fileName);

            if (File.Exists(fileName) == false)
            {
                SqlCeEngine db = new SqlCeEngine(glob.DBConnection);
                db.CreateDatabase();

                using (SqlCeConnection connection = new SqlCeConnection(glob.DBConnection))
                {
                    try
                    {
                        connection.Open();
                    }
                    catch (Exception ex)
                    {
                        glob.kernel.Panic(glob.PanicType.db_connect, ex);
                    }

                    foreach (string s in Flare.Properties.Resources.generate_table.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        using (SqlCeCommand command = new SqlCeCommand(s, connection))
                        {
                            try
                            {
                                command.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(command.CommandText + "\n" + ex.Message);
                                break;
                            }
                        }
                    }
                }
            }

            App.Current.Exit += (s, m) =>
            {
                Flare.Properties.Settings.Default.Save();
            };

#if (DEBUG != true)
            DispatcherUnhandledException += AppDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
#endif
        }

        private void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            glob.kernel.Panic(glob.PanicType.other, e.Exception);
            e.Handled = true;
        }

        private void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            glob.kernel.Panic(glob.PanicType.other, null);
        }

    }
}
